<?php 
//all the class/function includes are managed in the includer file
include("include/includer.php");
//include the rss feed parser
require_once('magpierss72/rss_fetch.inc');

//get all the configuration variables (custom function in newzbook.php include)
getConfigVars();  
$action = $category = $path = $showid = $season = $command = $artistid = $albumid = null;
//Get all the URL parameters (_GET)
if(isset($_GET['action'])) {
  $action = $_GET['action'];
}
if(isset($_GET['category'])) {
	$category = $_GET['category'];
}
if(isset($_GET['path'])) {
	$path = $_GET['path'];
}
if(isset($_GET['showid'])) {
	$showid = $_GET['showid'];
}
if(isset($_GET['season'])) {
	$season = $_GET['season'];
}
if(isset($_GET['command'])) {
	$command = $_GET['command'];
}
if(isset($_GET['artistid'])) {
	$artistid = $_GET['artistid'];
}
if(isset($_GET['albumid'])) {
	$albumid = $_GET['albumid'];
}


//setup the XBMC URL
$XBMC_commandURL = "http://$config_xbmc_username:$config_xbmc_password@$config_xbmc_location:$config_xbmc_port/xbmcCmds/xbmcHttp?command=";

function modifyQueueByDatabase($qtype,$query){
	global $action, $XBMC_commandURL;
	//echo "QTYPE IS: $qtype <br />";
	//echo "QUERY IS: $query <br />";
	//echo "ACTION IS: $action <br />";
	//which playlist should we workwith
	if($qtype=="songs" || $qtype=="musicvideos"){
		$playlistID = 0;
	}else if($qtype=="movies" || $qtype=="episodes"){
		$playlistID = 1;
	}
	
	if($action == "playall"){
		//clear the current playlist
		$requestURL = $XBMC_commandURL . urlencode("ClearPlayList($playlistID)");
		file_get_contents($requestURL);
		//echo "Clearing current playlist and adding new $qtype... <br />";
	}
	//queue list of all songs for the artist
	$requestURL = $XBMC_commandURL . urlencode("AddToPlayListFromDB($qtype;$query)");
	file_get_contents($requestURL);
	
	//set the playlist to music
	//echo "Setting the playlist to music... <br />";
	$requestURL = $XBMC_commandURL . urlencode("SetCurrentPlaylist($playlistID)");
	file_get_contents($requestURL);
	
	//if the user wants to play the new items
	if($action == "playall"){
		//we will have cleared out the old playlist, so let's reset the playlist position to -1
		$requestURL = $XBMC_commandURL . urlencode("SetPlaylistSong(-1)");
		file_get_contents($requestURL);
	}
	//if the playlist isn't already playing, let's start it
	$tmp = file_get_contents($XBMC_commandURL . getcurrentlyplaying);
	//echo "<pre>$tmp</pre>";
	$tmp = explode("<li>",$tmp);
	foreach($tmp as $key => $val){ 
		$val = explode(":",$val,2);
		$nowplaying[$val[0]] = trim($val[1]);
	}
	//clear out the temporary array
	unset($tmp);
	
	/*
	if(isset($nowplaying['PlayStatus'])){
		echo "Play Status is: " . $nowplaying['PlayStatus'] . "<br /.";
	}else{
		echo "Play Status NOT SET <br />";
	}
	*/
	
	//only start things playing if we aren't already playing
	if(!isset($nowplaying['PlayStatus'])){
		//start playing
		$requestURL = $XBMC_commandURL . urlencode("PlayNext");
		file_get_contents($requestURL);
	}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<HEAD>
    <?php standardHead("XBMC Media Player"); ?>
	<link type="text/css" href="style/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />	
	<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
	<style>
		#XBMC_listing>H3{
			padding-right:35px;
		}
		.queueall{ margin-left:3px; }
		.playall, .queueall{
			display:block;
			float:right;
			height:30px;
			width:30px;
			border:1px solid #888;
			-webkit-border-radius:8px;
			position:relative;
			top:-35px;
			margin:0px 0px 0px 3px;
			padding:0px;
			background-position:50% 50%;
			-webkit-box-shadow:-3px 3px 5px #888;
			z-index:10;
		}
		.ui-tabs .ui-tabs-panel {
			padding:0px;
		}
		.ui-widget {
			font-size: 0.9em;
		}
		.ui-tabs .ui-tabs-nav li a {
			padding:0.5em 0.15em;
			font-size:0.75em;
		}
		/*
		#tabs { height: 300px; } 
		.tabs-bottom { position: relative; } 
		.tabs-bottom .ui-tabs-panel { height: 260px; overflow: auto; } 
		.tabs-bottom .ui-tabs-nav { position: absolute !important; left: 0; bottom: 0; right:0; padding: 0 0.2em 0.2em 0; } 
		.tabs-bottom .ui-tabs-nav li { margin-top: -2px !important; margin-bottom: 1px !important; border-top: none; border-bottom-width: 1px; }
		.ui-tabs-selected { margin-top: -3px !important; }
		*/
		#np_controls {
			margin: 10px 0px;
		}
		#np_controls a {
			border:1px solid #888;
			-webkit-border-radius:5px;
			padding:7px 10px 2px;
			margin-right:3px;
		}
	</style>
	<script type='text/javascript'>
	  $(function() {
		//Scroll to the proper location
		var offset = $("#pageTitle").offset().top;
		$('html,body').animate({scrollTop: offset}, 0);
		
		//setup the tabs
		$tabs = $("#tabs").tabs();
		$( ".tabs-bottom .ui-tabs-nav, .tabs-bottom .ui-tabs-nav > *" )
			.removeClass( "ui-corner-all ui-corner-top" )
			.addClass( "ui-corner-bottom" );

		<?php if(isset($_GET['tab'])){ ?>
			//select the tab based on the page request
			$tabs.tabs('select', '#<?php echo $_GET['tab']; ?>');
		<?php } ?>
	  });
	  </script>
</HEAD>

<BODY>
<?php internetSecurity(); ?>
<div style="visibility:hidden;display:none;" id="progress"><div id="progress_bg"></div><a name="loading" /><div id="progress_box"><img id="progress_image" style="padding-left:5px;padding-top:5px;" src="images/ajax-loader.gif" alt="loading...">Your request is being processed...</div></div>
<div class="headercontent">
  <?php headerContent(); ?>
</div>
<div class="maincontent">
  Please send any questions or comments to <?php echo "<a href='mailto:".$cfg->get("Owner","email")."'>".$cfg->get("Owner","firstname")." ".$cfg->get("Owner","lastname")."</a>";?>.
  <br />
<?php 

/*
//mobile or not
if($mobile){
    echo "This appears to be a mobile device.";
    }
elseif($_SERVER['REMOTE_ADDR'] == "127.0.0.1"){
    echo "<h1>Looks like you are on the popcornhour.</h1>";
}
else {
    echo "This appears to be a standard browser.";
}
*/
?>
	<div class="block">
	  <h2 id="pageTitle">XBMC</h2>
	  <div id="tabs">
		<ul>
			<li><a href="#XBMC_navigation">NAV</a></li>
			<li><a href="#XBMC_listing">LIST</a></li>
			<li><a href="#XBMC_nowplaying">PLAY</a></li>
			<li><a href="#XBMC_other">...</a></li>
		</ul>
		<div id="XBMC_navigation">
		  <h3>Database:</h3>
		  <ul class='filelist'>
			  <li class='icon icon_video'><a href='filemanXBMC.php?category=movie&action=viewdatabase&tab=XBMC_listing'>Movies</a>
			  <li class='icon icon_tv'><a href='filemanXBMC.php?category=TV&action=viewdatabase&tab=XBMC_listing'>TV</a>
			  <li class='icon icon_audio'><a href='filemanXBMC.php?category=music&action=viewdatabase&tab=XBMC_listing'>Music</a>
			  <li class='icon icon_folder'><a href='filemanXBMC.php?action=viewfiles&tab=XBMC_listing'>Files</a>
		  </ul>
		</div>
		<div id="XBMC_listing">
			
			<?php
			if($action == "play"){
				//send the request to play the file
				$requestURL = $XBMC_commandURL . urlencode("PlayFile($path)");				
				echo "Requesting $requestURL <br />";
				echo file_get_contents($requestURL);
			}
			else if($action == "playall" || $action == "queueall"){
				//AddToPlayListFromDB(type;statement) 
				//TYPE = songs, movies, episodes
				//STATEMENT is the WHERE clause
				//AddToPlayListFromDB(songs;idAlbum=362)
				switch($category){
					case "movie":
						//might add this later
						break;
					case "TV":
						//might add this later
						break;
					case "TVseason":
						//get the list of all episodes for the whole show
						
						break;
					case "TVepisode":
						//get the list of episodes for the show based on the season selected
						
						break;
					case "music":
						//might add this later (PARTY MODE?)
						$requestURL = $XBMC_commandURL . urlencode("ExecBuiltIn(PlayerControl(Partymode(music)))");
						echo file_get_contents($requestURL);
						break;
					case "album":
						$query = "idartist=$artistid";
						modifyQueueByDatabase("songs",$query);
						break;
					case "song":
						//get the list of all songs for the artist in the specified album
						$query = "idalbum=$albumid";
						modifyQueueByDatabase("songs",$query);
						break;
				}
			}
			else if($action == "viewfiles"){
			?>
			<h3>Files</h3>
			<ul class="filelist">
			  <li class='icon icon_audio'><a href='filemanXBMC.php?category=music&tab=XBMC_listing'>Music</a>
			  <li class='icon icon_video'><a href='filemanXBMC.php?category=video&tab=XBMC_listing'>Video</a>
			  <li class='icon icon_photo'><a href='filemanXBMC.php?category=pictures&tab=XBMC_listing'>Pictures</a>
			  <li class='icon icon_folder'><a href='filemanXBMC.php?category=files&tab=XBMC_listing'>Files</a>
			<?php
			}
			else if($action == "viewdetails"){
				//get the details for the requested database file
				if($category == "movie" || category == "TVepisode"){
					//get movie details
				}else if($category == "song"){
					//should we even do individual songs?
				}
			}
			else if($action == "download"){
				//send the request to play the file
				$requestURL = $XBMC_commandURL . urlencode("FileDownload($path;'bare')");				
				echo "Requesting $requestURL <br />";
				echo "<pre>";
				echo base64_decode(file_get_contents($requestURL));
				echo "</pre>";
			}
			else if($action == "viewdatabase"){
				//setup the encoding the way we want
				$requestURL = $XBMC_commandURL . urlencode("SetResponseFormat(webheader;false;webfooter;false;closeRecord;</record>;openField; ;closeField;</field>)");
				//Items removed from formatting
				//header; ?xml version='1.0' encoding='UTF-8' ?;
				//openRecordSet;<recordset>;closeRecordSet;</recordset>;
				//openField;<field>;
				//openRecord;<record>;
				
				//echo "setting the record format <a href='$requestURL'>link</a> <br />";
				if(file_get_contents($requestURL) != FALSE){
					if($category == "movie"){
						//setup the sql query
						$sqlQuery = "select c00, strPath, strFilename from movieview ORDER BY c00 ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "TV"){
						//setup the sql query
						$sqlQuery = "select c00, idShow from tvshow ORDER BY c00 ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "TVseason"){
						//setup the sql query
						//tvshow: c12 = season, 
						//tvshowlinkepisode
						$sqlQuery = "select distinct c12, idShow from episodeView where idShow = $showid ORDER BY c12 ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "TVepisode"){
						//select strTitle || " - " c00, strPath, strFileName from episodeview
						//setup the sql query
						$sqlQuery = "select strTitle || ' - ' || c00, strPath, strFileName, c13 from episodeview
										where idShow = $showid and c12 = $season ORDER BY cast(c13 as int) ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");				
					}
					else if($category == "music"){
						//setup the sql query
						//$sqlQuery = "select idArtist, strArtist from artist"; //shows all artists (including those who didn't lead an album)
						$sqlQuery = "select distinct idArtist, strArtist from albumview ORDER BY strArtist ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");				
					}
					else if($category == "album"){
						//setup the sql query
						$sqlQuery = "select idAlbum, strAlbum from album where idArtist=$artistid ORDER BY strAlbum ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");				
					}
					else if($category == "song"){
						//setup the sql query
						$sqlQuery = "select strTitle, strPath || strFileName, iTrack from songview where idArtist=$artistid and idAlbum=$albumid ORDER BY cast(iTrack as int) ASC";
						//setup the request for the content
						$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");				
					}
					//echo "going to fetch <a href='$requestURL'>link</a> <br />";
					//get the full listing
					$listing = file_get_contents($requestURL);
					//break out each of the items by record
					$listing = explode("</record>",$listing);
					array_pop($listing);
					
					//switch type and load header
					switch($category){
							case "movie":
								echo "<h3>Movies</h3>";
								break;
							case "TV":
								echo "<h3>TV Shows</h3>";
								break;
							case "TVseason":
								$sqlQuery = "select distinct strTitle from episodeview where idshow = $showid";
								$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");
								$showname = file_get_contents($requestURL);
								echo "<h3>$showname</h3>";
								break;
							case "TVepisode":
								$sqlQuery = "select distinct strTitle from episodeview where idshow = $showid";
								$requestURL = $XBMC_commandURL . urlencode("queryvideodatabase($sqlQuery)");
								$showname = file_get_contents($requestURL);
								echo "<h3>$showname - Season $season</h3>";
								break;
							case "music":
								echo "<h3>Artists</h3>";
								echo "<a href='filemanXBMC.php?category=$category&action=playall&tab=XBMC_nowplaying' class='playall icon icon_wand'></a>";
								break;
							case "album":
								$sqlQuery = "select strArtist from artist where idartist = $artistid";
								$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");
								$artist = file_get_contents($requestURL);
								echo "<h3>$artist Albums</h3>";
								echo "<a href='filemanXBMC.php?category=$category&artistid=$artistid&action=queueall&tab=XBMC_nowplaying' class='queueall icon icon_add'></a>";
								echo "<a href='filemanXBMC.php?category=$category&artistid=$artistid&action=playall&tab=XBMC_nowplaying' class='playall icon icon_pause'></a>";
								break;
							case "song":
								$sqlQuery = "select distinct strArtist || ' - ' || strAlbum from songview where idArtist = $artistid and idAlbum = $albumid";
								$requestURL = $XBMC_commandURL . urlencode("querymusicdatabase($sqlQuery)");
								$artistAndAlbum = file_get_contents($requestURL);
								echo "<h3>$artistAndAlbum</h3>";			
								echo "<a href='filemanXBMC.php?category=$category&albumid=$albumid&action=queueall&tab=XBMC_nowplaying' class='queueall icon icon_add'></a>";
								echo "<a href='filemanXBMC.php?category=$category&albumid=$albumid&action=playall&tab=XBMC_nowplaying' class='playall icon icon_pause'></a>";
								break;
					}
					echo "<ul class='filelist'>";
					
					//loop through each record and build out the HTML
					foreach($listing as $item){
						$item = explode("</field>",$item);
						switch($category){
							case "movie":
								echo "<li class='icon icon_video'><a href='filemanXBMC.php?path=$item[1]$item[2]&action=play&tab=XBMC_nowplaying'>$item[0]</a>";
								break;
							case "TV":
								echo "<li class='icon icon_folder'><a href='filemanXBMC.php?category=TVseason&action=viewdatabase&showid=$item[1]&tab=XBMC_listing'>$item[0]</a>";
								break;
							case "TVseason":
								echo "<li class='icon icon_folder'><a href='filemanXBMC.php?category=TVepisode&action=viewdatabase&showid=$item[1]&season=$item[0]&tab=XBMC_listing'>Season $item[0]</a>";
								break;
							case "TVepisode":
								echo "<li class='icon icon_video'><a href='filemanXBMC.php?path=$item[1]$item[2]&action=play&tab=XBMC_nowplaying'>$item[3]. $item[0]</a>";
								break;
							case "music":
								echo "<li class='icon icon_audio'><a href='filemanXBMC.php?category=album&action=viewdatabase&artistid=$item[0]&tab=XBMC_listing'>$item[1]</a>";
								break;
							case "album":
								echo "<li class='icon icon_audio'><a href='filemanXBMC.php?category=song&action=viewdatabase&artistid=$artistid&albumid=$item[0]&tab=XBMC_listing'>$item[1]</a>";
								break;
							case "song":
								echo "<li class='icon icon_audio'><a href='filemanXBMC.php?path=$item[1]&action=play&tab=XBMC_nowplaying'>$item[2]. $item[0]</a>";
								break;
						}
					}
				}
				
				//then change the encoding back
				$requestURL = $XBMC_commandURL . urlencode("SetResponseFormat()");
				file_get_contents($requestURL);
			}		
			else{
			/**********************\
			 *  Basic File View   *
			\**********************/
				if(isset($category)){
						//setup the request URL
						$requestURL = $XBMC_commandURL . urlencode("GetMediaLocation($category;$path)");				
						
						//make the request
						$listing = file_get_contents($requestURL);
						
						//convert it to an array by spliting on <li>
						$listing = explode("<li>",$listing);
						//remove the first item from the array since it will be blank (due to the <li> at the start)
						array_shift($listing);
						echo "<ul class='filelist'>";
						//loop through the items and create the HTML
						foreach($listing as $item){
							//break out the individual peices of the item (Label,Path,#)
							//echo "<li>$item<ul>";
							$item = explode(";",$item);
							//if the # is 1 then it's a listable path
							if($item[2] == 1){
								echo "<li class='icon icon_folder'><a href='filemanXBMC.php?category=$category&path=".urlencode($item[1])."&tab=XBMC_listing'>$item[0]</a>";
							}
							else if($item[2] == 0){
								echo "<li class='icon icon_view'><a href='filemanXBMC.php?category=$category&path=".urlencode($item[1])."&action=play&tab=XBMC_nowplaying'>$item[0]<img src='./images/control_play.png'></a>";
								echo " <a href='filemanXBMC.php?category=$category&path=".urlencode($item[1])."&action=download&tab=XBMC_listing'><img src='./images/disk.png'></a>";
							}
							else{
								echo "<li>$item[0]";
							}
							//echo "</ul>";
						}
						echo "</ul>";
						//echo file_get_contents($XBMC_commandURL . "GetShares($category)");
				}
				else{
					echo "Select a category or section from the NAV tab to see a listing of the files.";
				}
			}
			?>
			</ul>
		</div>
		<div id="XBMC_other">
			<p>This is the other section.</p>
		</div>
		<div id="XBMC_nowplaying">
		Now Playing:  <br />
		<div class='xbmc_nowplaying'>
		<?php
		echo "<div id='np_controls'>";
		displayController(null,"filemanXBMC.php?action=remotecontrol","&tab=XBMC_nowplaying");
		if($action == "remotecontrol"){
			switch($command){
				case "play":
					$commandf = "Pause"; //is there a play?
					break;
				case "pause":
					$commandf = "Pause";
					break;
				case "stop":
					$commandf = "Stop";
					break;
				case "rew":
					$commandf = "SetPlaySpeed(-1)";
					break;
				case "fwd":
					$commandf = "SetPlaySpeed(1)";
					break;
				case "next":
					$commandf = "PlayNext";
					break;
				case "prev":
					$commandf = "PlayPrev";
					break;
			}
			$requestURL = $XBMC_commandURL . urlencode($commandf);				
			file_get_contents($requestURL);
		}
		else if($action == "setplaylistsong"){
			if(isset($_GET['itemid'])){
				$itemid = $_GET['itemid'];
			}
			$requestURL = $XBMC_commandURL . urlencode("SetPlaylistSong($itemid)");
			file_get_contents($requestURL);
		}
		echo "</div>";
		
		
		//file_get_contents($XBMC_commandURL . getcurrentlyplaying);
		$tmp = file_get_contents($XBMC_commandURL . "getcurrentlyplaying");
		//echo "<pre>$tmp</pre>";
		$tmp = explode("<li>",$tmp);
		foreach($tmp as $key => $val){ 
			$val = explode(":",$val,2);
			if(isset($val[1])){
				$nowplaying[$val[0]] = trim($val[1]);
			}
		}
		//clear out the temporary array
		unset($tmp);
		
		if(isset($nowplaying['Type'])){
			//setup the now playing section
			if($nowplaying['Type'] == 'Video'){
				echo "<div class='icon icon_video' style='padding-left:20px;background-position:0% 50%;height:20px;display:inline;'></div>";
			}
			
			//setup the headline info
			echo "<div>";
			echo "<span id='np_title'>".$nowplaying['Title'] . "</span> (<span id='np_time'>".$nowplaying['Time']."</span>) <span id='np_percentage'>".$nowplaying['Percentage']."</span>%";
			echo "</div>";
		}
		
		//try to create the thumb
		//FileDownload()
		//$nowplaying['Thumb'];
		echo "<br />";
		
		if(isset($nowplaying['Plot'])){
			//setup the plot
			echo "<div>";
			echo "Plot: <span id='np_plot'>".$nowplaying['Plot']."</span>";
			echo "</div>";
		}
		
		$requestURL = $XBMC_commandURL . urlencode("GetPlaylistContents()");
		$tmp = file_get_contents($requestURL);
		if(!strstr($tmp,"[Empty]")){
			echo "<ul class='filelist'>";
			$tmp = explode("<li>",$tmp);
			array_shift($tmp);
			$i = 0;
			foreach($tmp as $item){
				//echo "<br />".$item;
				$item = explode("\n",$item); //ensure the final item doesn't get HTML attached to it
				$item = $item[0];
				$requestURL = $XBMC_commandURL . urlencode("GetTagFromFilename($item)");
				//echo "<br /><a href='$requestURL'>$requestURL</a>";
				//echo "<pre>";
				$tmp2 = file_get_contents($requestURL);
				//echo $tmp2;
				$tmp2 = explode("<li>",trim($tmp2));
				array_shift($tmp2);
				foreach($tmp2 as $item2){
					foreach($tmp2 as $key => $val){ 
						$val = explode(":",$val,2);
						$playlist[trim($val[0])] = trim($val[1]);
					}
				}
				
				if(isset($playlist['Artist'])){
					echo "<li class='icon icon_view'><a href='filemanXBMC.php?action=setplaylistsong&itemid=$i&tab=XBMC_nowplaying'>".$playlist['Artist']. " - " . $playlist['Title'] ."</a>";
				}
				$i++;
			}
			echo "</ul>";
		}
		
		//closing div for the nowplaying class
		echo "</div>";
		?>
		</div>
	</div>
<?php

?>
</div>
</BODY>